import React, { useState, useEffect } from 'react'
import axios from 'axios';
import { withRouter } from "react-router-dom";//{高阶组件}可以拿到根路由的所有方法
import './index.model.css'
import {
  UserOutlined,
  HomeOutlined,
  UserDeleteOutlined,
  ExclamationCircleOutlined,
  OrderedListOutlined,
  UnorderedListOutlined,
  GlobalOutlined,
  EditOutlined,
  SnippetsOutlined,
  AlignCenterOutlined,
  IssuesCloseOutlined,
  CheckCircleOutlined,
  CloudOutlined,
  LoadingOutlined,
  CloudUploadOutlined,
  CloudDownloadOutlined
} from '@ant-design/icons';
import { Layout, Menu } from 'antd';
import { connect } from 'react-redux';
const { SubMenu } = Menu;
const { Sider } = Layout;


// 模拟数组结构
//  function getItem(label, key, icon, children, type) {
//    return {
//      key,
//      icon,
//      children, 
//      label,
//      type,
//    };
//  }
/**
 * getItem("label","key","icon",children:Array)
 */
//  const items = [
//    getItem('首页', '/home', <UserOutlined />),
//    getItem('用户管理', '/user-manage', <AppstoreOutlined />, [getItem('用户列表', '/user-manage/list', <UserOutlined />)]),
//    getItem('权限管理', '/right-manage', <SettingOutlined />, [
//      getItem('角色列表', '/right-manage/role/list', <UserOutlined />),
//      getItem('权限列表', '/right-manage/right/list', <UserOutlined />),
//    ]),
//    getItem('Group', 'grp', null, [getItem('Option 13', '13'), getItem('Option 14', '14')], 'group'),
//  ];


// 模拟数组结构
// const MenuList = [
//   {
//     title: "首页",
//     key: "/home",
//     icon: <UserOutlined />
//   },
//   {
//     title: '用户管理',
//     key: '/user-manage',
//     icon: <AppstoreOutlined />,
//     children: [
//       {
//         title: '用户列表',
//         key: '/user-manage/list',
//         icon: <UserOutlined />
//       }
//     ]
//   },
//   {
//     title: '权限管理',
//     key: '/right-manage',
//     icon: <SettingOutlined />,
//     children: [
//       {
//         title: '角色列表',
//         key: '/right-manage/role/list',
//         icon: <UserOutlined />
//       },
//       {
//         title: '权限列表',
//         key: '/right-manage/right/list',
//         icon: <UserOutlined />
//       }
//     ]
//   }
// ]

const iconList = {
  '/home': <HomeOutlined />,
  '/user-manage': <UserOutlined />,
  '/user-manage/list': <UserDeleteOutlined />,
  '/right-manage': <ExclamationCircleOutlined />,
  '/right-manage/role/list': <OrderedListOutlined />,
  '/right-manage/right/list': <UnorderedListOutlined />,
  '/news-manage': <GlobalOutlined />,
  '/news-manage/add': <EditOutlined />,
  '/news-manage/draft': <SnippetsOutlined />,
  '/news-manage/category': <AlignCenterOutlined />,
  '/audit-manage': <IssuesCloseOutlined />,
  '/audit-manage/audit': <CheckCircleOutlined />,
  '/audit-manage/list': <OrderedListOutlined />,
  '/publish-manage': <CloudOutlined />,
  '/publish-manage/unpublished': <LoadingOutlined />,
  '/publish-manage/published': <CloudUploadOutlined />,
  '/publish-manage/sunset': <CloudDownloadOutlined />
}

const SideMenu = (props) => {
  const { role: { rights } } = JSON.parse(localStorage.getItem("token"));



  // 将json-server中获取到的数据存放到menu中
  const [menu, setMenu] = useState([])

  // 从json-server后端接口中获取数据
  useEffect(() => {
    axios.get("/rights?_embed=children").then((res) => {
      // console.log(res.data);
      setMenu(res.data);//使用setMenu方法将数据存放到menu中
    })
  }, [])

  // 判断数据中是否包含pagepermisson，包含的话 如果等于1，则显示在一级路由中，如果没有则不显示
  const checkPagePermission = (item) => {
    return item.pagepermisson && rights.includes(item.key)
  }

  // 将需要渲染的数据使用map遍历输出
  const renderMenu = (MenuList) => {
    return MenuList.map(item => {
      if (item.children?.length > 0 && checkPagePermission(item)) {
        return <SubMenu key={item.key} icon={iconList[item.key]} title={item.title}>
          {renderMenu(item.children)}
        </SubMenu>
      }

      return checkPagePermission(item) && <Menu.Item key={item.key} icon={iconList[item.key]} onClick={() => {
        // 使用高阶组件withRouter得到
        props.history.push(item.key)
      }}>{item.title}</Menu.Item>
    })
  }

  // 选中的选项高亮
  const SelectKeys = [props.location.pathname]
  // 选中的高亮如果是展开项，高亮的时候刷新完成后继续展开
  const openKeys = ["/" + props.location.pathname.split("/")[1]]

  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div style={{ display: "flex", height: "100%", flexDirection: "column" }}>
        <div className="demo-logo-vertical" >全球新闻发布管理系统</div>

        <div style={{ flex: 1, overflow: "auto" }}>
          {/* 

  使用模板：getItem
    <Menu
    theme="dark"
    mode="inline"
    defaultSelectedKeys={['/home']}
    items={items}
  /> 直接渲染items

*/}
          {/* <Menu
    theme="dark"
    mode="inline"
    defaultSelectedKeys={['/home']}
    items={items}
    onClick={({key})=>{
      // 使用高阶组件withRouter得到
      props.history.push(key)
    }}
  /> */}


          {/* 

  使用的模板：
    <Menu>
      没有下拉选项
        <Menu.Item key icon > title </Menu.Item>
      如果有下拉选项
      <SubMenu key title icon>
        <Menu.Item key icon > title </Menu.Item>
      </SubMenu>
    </Menu>

*/}
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={SelectKeys}
            defaultOpenKeys={openKeys}
          >
            {renderMenu(menu)}
          </Menu>
        </div>
      </div>
    </Sider>
  )
}

const mapStateToProps = ({ CollapsedReducers: { isCollapsed } }) => ({
  isCollapsed
})

export default connect(mapStateToProps)(withRouter(SideMenu))  
